<template>
  <van-popup slot="fr-ext" v-model="popup" class="lc-fullscreen-popup">
    <div class="lc-fixed-top">
      <van-nav-bar
        :title="actionName=='agree'?'同意':'反对'"
        :left-text="$t('close')"
        left-arrow
        fixed
        @click-left="closePopup"
      />
      <van-cell-group
        v-if="(actionName==='agree'|| actionName==='oppose')
        &&(options.directHandlerSign === 'true' || options.directHandlerSign === true)">
        <van-cell>
          <template slot="title">
            <span class="van-cell-text">直接处理</span>
            <van-icon name="question-circle" size="18px " @click="showWarnMessage"/>
            <!-- <van-tag type="danger" @click="showWarnMessage">?</van-tag> -->
          </template>
          <van-switch v-model="checked" size="20px" />
        </van-cell>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-show="!options.hideOpinion===true"
          v-model="form.opinion"
          :label="opinionLabel"
          type="textarea"
          placeholder="请输入意见"
          rows="4"
          autosize
        />
      </van-cell-group>
			
			<!-- 录音 -->
			<div class="record" v-show="actionName==='agree'">
				<audio controls></audio>
				<button v-if="recorderText=='start'" @click="startRecording">开始录音</button>
				<button v-if="recorderText=='stop'" @click="stopRecording">停止录音</button>
				<button v-if="recorderText=='cancel'" @click="cancelAudio">取消录音</button>
			</div>
			
      <van-cell-group v-if="actionName==='agree'">
        <van-lc-checker
          v-show="jumpOptionShow"
          v-model="jumpType"
          :options="jumpOption"
          label="多选器"
          type="radio"
          checker
        />

        <div v-show="(jumpType==='free'||jumpType==='select')&&(options.hidePath==='false'||options.hidePath===false)">
          <van-lc-radio
            v-model="destination"
            :label="pathLabel"
            :options="path"
            placeholder="请选择"
            clearable
            required
          />
          <van-lc-checkbox
            v-model="userCheck"
            :label="userLabel"
            :options="user"
            placeholder="请选择"
            store="array"
            clearable
            required
          />
        </div>
        <div
          v-for="(item,index) in commonPath"
          v-show="jumpType==='common'&&(options.hidePath==='false'||options.hidePath===false)"
          :key="item.nodeId+index">
          <van-cell :value="item.name" title="路径" />
          <van-lc-checkbox
            v-model="commonUserCheck[item.nodeId]"
            :label="userLabel"
            :options="commonUser[item.nodeId]"
            placeholder="请选择"
            store="array"
            value-key="id"
            label-key="name"
          />
        </div>
      </van-cell-group>

    </div>
    <lc-toolbar :actions="actions"/>
  </van-popup>

</template>

<script>
import Vue from 'vue'
import LcControl from '@/components/LcControl'
Vue.use(LcControl)
import { complete } from '@/api/platform/bpmn/action'
import { toAgree } from '@/api/platform/bpmn/bpmn'
import LcToolbar from '@/components/LcToolbar'
import HZRecorder from '@/utils/record.js' // 录音脚本
import Common from '@/components/common.vue'
export default {
  components: {
    LcToolbar
  },
  props: {
    value: Boolean,
    taskId: String,
    bpmnInstId: String,
    data: [Object, String],
    actionName: String,
    version: Number
  },
  data() {
    return {
      popup: false,
      opinionLabel: '',
      form: {
        data: '',
        taskId: this.taskId,
        actionName: this.actionName,
        opinion: '',
        backHandMode: 'direct',
        destination: '',
        version: 0,
        nodeUsers: []
      },
      options: {},
      path: [],
      user: [],
      userCheck: [],
      commonPath: [],
      commonUser: [],
      commonUserCheck: [],
      jumpOption: [],
      jumpType: 'common',
      jumpOptionShow: false,
      pathLabel: '路径',
      userLabel: '执行人',
      destination: '',
      actions: [{
        'name': this.$t('common.button.save'),
        'buttonType': 'primary',
        'callback': this.onSelect
      }],
      checked: false,
			recorder: null, // 录音对象
			recorderText: 'start', // 录音按钮显示 'start'开始 'stop'停止 'cancel'取消
    }
  },
  watch: {
    value() {
      this.popup = this.value
      if (this.popup) {
        this.loadData()
      }
    },
    jumpType() {
      if (this.$utils.isEmpty(this.jumpType)) {
        this.jumpType = 'common'
      }
      this.destination = ''
      if (this.jumpType === 'select') {
        this.initPath(this.options.outgoingNodes)
      } else if (this.jumpType === 'free') {
        this.initPath(this.options.allNodeDef)
      }
    },
    destination() {
      this.form.destination = this.destination
      if (this.jumpType === 'common') {
        this.commonPath = this.options.pathOutgoingNodes
        this.initCommonUser(this.options.pathOutgoingNodesUsersMap)
        this.commonUser = this.options.pathOutgoingNodesUsersMap
      } else if (this.jumpType === 'select') {
        this.initUser(this.options.outgoingNodesUsersMap)
      } else if (this.jumpType === 'free') {
        this.initUser(this.options.allNodeDefUsersMap)
      }
    },
    checked() {
      if (this.checked === 'true' || this.checked === true) {
        this.form.directHandlerSign = true
      } else {
        this.form.directHandlerSign = false
      }
    }
  },
  methods: {
    closePopup() {
      this.$emit('input', false)
    },
    onSave(data) {
      complete(data).then(response => {
        this.$emit('after-script', this.actionName)
        this.$toast.success(`操作成功！`)
        this.$router.push({ path: '/bpmn/pending' })
      }).catch(error => {
        console.error(error.cause)
      })
    },
    loadData() {
      this.initOpinionLabel()
      toAgree({
        taskId: this.taskId,
        actionName: this.actionName
      }).then(response => {
        this.options = response.data
        this.initData()
      }).catch(error => {
        console.error(error)
      })
    },
    initOpinionLabel() {
      // 设置意见文本
      if (this.actionName === 'agree') {
        this.opinionLabel = '审批意见'
      } else if (this.actionName === 'oppose') {
        this.opinionLabel = '反对意见'
      } else if (this.actionName === 'abandon') {
        this.opinionLabel = '弃权原因'
      } else if (this.actionName === 'agreeTrans') {
        this.opinionLabel = '审批意见'
      } else if (this.actionName === 'opposeTrans') {
        this.opinionLabel = '反对意见'
      }
    },
    initData() {
      const options = this.options

      // 设置默认常用语
      if (options.defaultCommonStatment) {
        this.form.opinion = options.defaultCommonStatment.value
      }

      this.form.taskId = options.taskId
      this.form.actionName = options.actionName
			console.log(this.form);
			
      // 还原数组，避免重新打开无限增加现象
      this.jumpOption = []
      if (options.jumpType.indexOf('common') !== -1) {
        this.jumpOption.push({ 'label': '正常跳转', 'value': 'common' })
      }
      if (options.jumpType.indexOf('select') !== -1) {
        this.jumpOption.push({ 'label': '选择路径跳转', 'value': 'select' })
      }
      if (options.jumpType.indexOf('free') !== -1) {
        this.jumpOption.push({ 'label': '自由跳转', 'value': 'free' })
      }

      if (this.jumpOption.length > 1) {
        this.jumpOptionShow = true
      }
      if (this.jumpType === 'common') {
        this.initCommonUser(options.pathOutgoingNodesUsersMap)
        this.commonPath = options.pathOutgoingNodes
        this.commonUser = options.pathOutgoingNodesUsersMap
      } else if (this.jumpType === 'select') {
        this.initPath(this.options.outgoingNodes)
      } else if (this.jumpType === 'free') {
        this.initPath(this.options.allNodeDef)
      }
    },
    onSelect(item) {
      const form = this.form
      form.data = JSON.stringify(this.data)
      form.destination = this.destination
      form.version = this.version
      if (this.actionName === 'agree') {
        form.nodeUsers = this.setNodeUsers()
      }

      this.onSave(this.form)
    },
    initPath(path) {
      this.path = []
      this.form.destination = ''
      for (var i = 0; i < path.length; i++) {
        this.path.push({ label: path[i].name, value: path[i].nodeId })
      }
    },
    initUser(users) {
      this.user = []
      this.userCheck = []
      if (this.$utils.isEmpty(this.destination)) return
      const temp = users[this.destination]
      for (var i = 0; i < temp.length; i++) {
        this.user.push({ label: temp[i].name, value: temp[i].id, 'type': temp[i].type })
        this.userCheck.push(temp[i].id)
      }
    },
    getIds(userArray) {
      if (this.$utils.isEmpty(userArray)) return
      const temp = []
      for (var i = 0; i < userArray.length; i++) {
        temp.push(userArray[i].id)
      }
      return temp
    },
    initCommonUser(data) {
      this.commonUserCheck = {}
      for (var variable in data) {
        this.commonUserCheck[variable] = this.getIds(data[variable])
      }
    },
    setNodeUsers() {
      const jumpType = this.jumpType ? this.jumpType : 'common'
      let userArray = []
      const nodeUsers = []
      let users = []
      let nodes = []
      let i = 0
      let j = 0
      if (jumpType === 'common') {
        users = this.options.pathOutgoingNodesUsersMap
        nodes = this.options.pathOutgoingNodes
        for (i = 0; i < nodes.length; i++) {
          userArray = []
          for (j = 0; j < users[nodes[i].nodeId].length; j++) {
            const user = users[nodes[i].nodeId][j]
            userArray.push({
              id: user.id,
              name: user.name,
              type: user.type,
              groupType: user.partyType || ''
            })
          }
          nodeUsers.push({
            jumpType: jumpType,
            nodeId: nodes[i].nodeId,
            executors: userArray
          })
        }
      } else {
        if (jumpType === 'select') {
          users = this.options.outgoingNodesUsersMap
        } else if (jumpType === 'free') {
          users = this.options.allNodeDefUsersMap
        }
        userArray = []
        for (i = 0; i < users[this.destination].length; i++) {
          const user = users[this.destination][i]
          userArray.push({
            id: user.id,
            name: user.name,
            type: user.type,
            groupType: user.partyType || ''
          })
        }
        nodeUsers.push({
          jumpType: jumpType,
          nodeId: this.destination,
          executors: userArray
        })
      }
      return JSON.stringify(nodeUsers)
    },
    showWarnMessage() {
      this.$dialog.alert({
        title: this.$t('common.dialog.warn'),
        message: `您拥有会签特权，可以对会签任务进行直接处理。`
      })
    },
		
		// 开始录音
		startRecording() {
			let that = this;
			HZRecorder.get(function (rec) {
				that.recorder = rec;
				that.recorder.start();
				that.recorderText = 'stop';
			});
		},
		// 停止录音
		stopRecording() {
			let audio = document.querySelector('audio');
			this.recorder.stop();
			this.recorder.play(audio);
			this.recorderText = 'cancel';
			
// 			this.recorder.getMp3Blob(function (blob) {
// 					log('MP3导出成功');
// 					mp3Blob = blob;
// 					var url = URL.createObjectURL(mp3Blob);
// 					var div = document.createElement('div');
// 					var au = document.createElement('audio');
// 					var hf = document.createElement('a');
// 					au.controls = true;
// 					au.src = url;
// 					hf.href = url;
// 					hf.download = new Date().toISOString() + '.mp3';
// 					hf.innerHTML = hf.download;
// 					div.appendChild(au);
// 					div.appendChild(hf);
// 					recordingslist.appendChild(div);
// 			});
			
			this.recorder.upload(Common.fileService+"/wav/mp/mp3/"+Common.wavFormId+"/"+this.taskId, function (state, e) {
			// this.recorder.upload("http://127.0.0.1:8014/wav/mp/mp3/"+Common.wavFormId+"/"+this.taskId, function (state, e) {
				switch (state) {
					case 'uploading':
						//var percentComplete = Math.round(e.loaded * 100 / e.total) + '%';
						break;
					case 'ok':
						//alert(e.target.responseText);
						// this.wav =  e.target.responseText;
						var rep = JSON.parse(e.target.responseText);
						console.log(rep)
						if(rep.code == 0){
							Common.wav = rep.result.key;
							alert("语音上传完成");	
						}else if(rep.code == 500){
							alert(rep.msg);
						}
						break;
					case 'error':
						alert("上传失败");
						break;
					case 'cancel':
						alert("上传被取消");
						break;
				}
			});
		},
		// 取消录音
		cancelAudio(){
			let audio = document.querySelector('audio');
			this.recorder.clear();
			this.recorder.play(audio);
			this.recorderText = 'start';
		}

  }

}
</script>
<style lang="scss" scoped>
/* 录音 */
.record {
	padding: 15px;
	background-color: #fff;
	audio {
		width: 100%;
		height: 40px;
		margin-bottom: 10px;
	}
	button {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 40px;
		margin-bottom: 10px;
		color: #fff;
		background: #38f;
		border: none;
		border-radius: 20px;
	}
}
</style>
